package com.ruoyi.coupon.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.CommonUtil;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.coupon.domain.CouponRecord;
import com.ruoyi.coupon.domain.JsonData;
import com.ruoyi.coupon.enums.BizCodeEnum;
import com.ruoyi.coupon.enums.CouponCategoryEnum;
import com.ruoyi.coupon.enums.CouponPublishEnum;
import com.ruoyi.coupon.enums.CouponStateEnum;
import com.ruoyi.coupon.exception.BizException;
import com.ruoyi.coupon.mapper.CouponRecordMapper;
import com.ruoyi.coupon.utils.RedisIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import com.ruoyi.coupon.mapper.CouponMapper;
import com.ruoyi.coupon.domain.Coupon;
import com.ruoyi.coupon.service.ICouponService;

import static com.ruoyi.common.core.context.SecurityContextHolder.THREAD_LOCAL;
import static com.ruoyi.coupon.utils.RedisConstants.SECKILL_STOCK_KEY;

/**
 * 优惠卷列表Service业务层处理
 *
 * @author 林道敬
 * @date 2024-12-31
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private CouponRecordMapper couponRecordMapper;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    @Override
    public JsonData seckillVoucher(Long voucherId) {
        Long userId = 1l;
        long orderId = redisIdWorker.nextId("order");
        System.out.println("orderId :"+orderId);
        // 1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );
        int r = result.intValue();
        // 2.判断结果是否为0
        if (r != 0) {
            // 2.1.不为0 ，代表没有购买资格
            return JsonData.buildError(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 3.返回订单id
        return JsonData.buildSuccess(orderId);
    }
    /**
     * 查询优惠卷列表
     *
     * @param id 优惠卷列表主键
     * @return 优惠卷列表
     */
    @Override
    public Coupon selectCouponById(Long id)
    {
        return couponMapper.selectCouponById(id);
    }

    /**
     * 查询优惠卷列表列表
     *
     * @param coupon 优惠卷列表
     * @return 优惠卷列表
     */
    @Override
    public List<Coupon> selectCouponList(Coupon coupon)
    {
        return couponMapper.selectCouponList(coupon);
    }

    /**
     * 新增优惠卷列表
     *
     * @param coupon 优惠卷列表
     * @return 结果
     */
    @Override
    public int insertCoupon(Coupon coupon)
    {
        coupon.setCreateTime(DateUtils.getNowDate());
        return couponMapper.insertCoupon(coupon);
    }

    /**
     * 修改优惠卷列表
     *
     * @param coupon 优惠卷列表
     * @return 结果
     */
    @Override
    public int updateCoupon(Coupon coupon)
    {
        return couponMapper.updateCoupon(coupon);
    }

    /**
     * 批量删除优惠卷列表
     *
     * @param ids 需要删除的优惠卷列表主键
     * @return 结果
     */
    @Override
    public int deleteCouponByIds(Long[] ids)
    {
        return couponMapper.deleteCouponByIds(ids);
    }

    /**
     * 删除优惠卷列表信息
     *
     * @param id 优惠卷列表主键
     * @return 结果
     */
    @Override
    public int deleteCouponById(Long id)
    {
        return couponMapper.deleteCouponById(id);
    }

    @Override
    public void addCoupon(long couponId, CouponCategoryEnum couponCategoryEnum) {
        Coupon couponDO = couponMapper.selectOne(new QueryWrapper<Coupon>()
                .eq("id", couponId)
                .eq("category", couponCategoryEnum.name()));
        System.out.println("couponDO: "+couponDO);
        //优惠券是否可以领取
        this.checkCoupon(couponDO, 1l);

        //构建领劵记录
        CouponRecord couponRecord = new CouponRecord();
        BeanUtils.copyProperties(couponDO, couponRecord);
        couponRecord.setCreateTime(new Date());
        couponRecord.setUseState(CouponStateEnum.NEW.name());
        couponRecord.setUserId(1l);
        couponRecord.setUserName("lindaojing");
        couponRecord.setCouponId(couponId);
        couponRecord.setId(null);

        //扣减库存
        int rows = couponMapper.reduceStock(couponId);

        //int flag = 1/0;

        if (rows == 1) {
            //库存扣减成功才保存记录
            couponRecordMapper.insert(couponRecord);

        } else {
            log.warn("发放优惠券失败:{},用户:{}", couponDO,"");
            throw new BizException(BizCodeEnum.COUPON_NO_STOCK);
        }

    }

    @Override
    public void addSeckillCoupon(Long couponId) {
        Coupon coupon = couponMapper.selectById(couponId);
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + couponId, coupon.getStock().toString());

    }

    /**
     * 校验是否可以领取
     * @param couponDO
     * @param
     */
    private void checkCoupon(Coupon couponDO, Long userId) {

        if (couponDO == null) {
            throw new BizException(BizCodeEnum.COUPON_NO_EXITS);
        }

        //库存是否足够
        if (couponDO.getStock() <= 0) {
            throw new BizException(BizCodeEnum.COUPON_NO_STOCK);
        }

        //判断是否是否发布状态
        if (!couponDO.getPublish().equals(CouponPublishEnum.PUBLISH.name())) {
            throw new BizException(BizCodeEnum.COUPON_GET_FAIL);
        }

        //是否在领取时间范围
        long time = CommonUtil.getCurrentTimestamp();
        long start = couponDO.getStartTime().getTime();
        long end = couponDO.getEndTime().getTime();
        if (time < start || time > end) {
            throw new BizException(BizCodeEnum.COUPON_OUT_OF_TIME);
        }

        //用户是否超过限制
        long recordNum = couponRecordMapper.selectCount(new QueryWrapper<CouponRecord>()
                .eq("coupon_id", couponDO.getId())
                .eq("user_id", userId));

        if (recordNum >= couponDO.getUserLimit()) {
            throw new BizException(BizCodeEnum.COUPON_OUT_OF_LIMIT);
        }
    }
}
